import network,time,sys
from machine import I2C,Pin
from ssd1306 import SSD1306_I2C
from neopixel import NeoPixel

red=(255,0,0)
green=(0,255,0)
blue=(0,0,255)
yellow=(200,200,0)
purple=(128,0,128)

led=Pin(2,Pin.OUT)
np=NeoPixel(Pin(0),10)
led.on()
i2c=I2C(-1,sda=Pin(5),scl=Pin(4),freq=400000)
lcd=SSD1306_I2C(128,64,i2c)
row=0
col=0
lcd.text('System ok.',0,row)
row+=8
lcd.show()
w=network.WLAN(network.STA_IF)

while not w.isconnected():
	time.sleep(1)
	continue

def get_color_from_msg(msg):
	data=msg.decode('asc')
	color_index=('red','green','blue')
	color=[0,0,0]
	for i in range(3):
		digit_pos=data.find(color_index[i])
		if digit_pos>0:
			color_str=data[digit_pos+len(color_index[i]):digit_pos+len(color_index[i])+3]
			if(color_str.isdigit()):
				color[i]=int(color_str)
			else:
				return
		else:
			return
	return color[0],color[1],color[2]

def get_color(msg):
	color=[0,0,0]
	color_str=''
	data=msg.decode('utf8')
	color_index=data.find(']')
	for i in range(3):
		color_str=data[color_index+1+2*i:color_index+3+2*i]
		color[i]=int(color_str,16)	
	return color[0],color[1],color[2]
	
def show_msg(topic,msg):
	global row
	global lcd
	
	if row>56:
		lcd.fill(0)
		row=0
	if len(msg.decode('asicii')) > 1:
		for i in range(int(len(msg.decode('asicii'))/16)+1):
			lcd.text(msg.decode('asicii')[i*16:(i+1)*16],0,row)
			row+=8
	else:
		lcd.text(msg.decode('asicii'),0,row)
		row+=8
	lcd.show()
def flash(a):
	if(led.value()):
		led.off()
	else:
		led.on()

def cb(topic,msg):
	if msg==b'on':
		led.off()
	elif msg==b'off':
		led.on()
	elif msg==b'f':
		flash(msg)
	elif msg==b'red':
		np.fill(red)
		np.write()
	elif msg==b'green':
		np.fill(green)
		np.write()
	elif msg==b'blue':
		np.fill(blue)
		np.write()
	elif msg==b'yellow':
		np.fill(yellow)
		np.write()
	elif msg==b'purple':
		np.fill(purple)
		np.write()
	elif msg.decode('asc').find('[color]') == 0:
		color=get_color(msg)
		print('color:',color)
		if(color!=None):
			np.fill(color)
			np.write()
	else:
		show_msg(topic,msg)

from simple import MQTTClient

error_timer=0
mq=MQTTClient('johnny','iot.yingeyun.com',1883,'TEST','TEST')
mq.set_callback(cb)
mq.connect()
mq.subscribe('/test/abc')

while True:
	time.sleep_ms(500)
	try:
		mq.wait_msg()
	except:
		error_timer=error_timer+1
		print('Error')
		mq.connect()
		mq.subscribe('/test/abc')

print('Error times:'+error_timer)
